﻿using AutoMapper;
using MediatR;
using SU.Center.Domain.RBAC;
using SU.Center.Infa;
using System.Transactions;

namespace SU.Center.Api.Handler.RBAC
{
    /// <summary>
    /// 删除角色
    /// </summary>
    public class DeleteRolesHandler:IRequestHandler<DeleteRolesReqsultDto,ApiResult>
    {
        private readonly IBaseReposiotry<Roles> _permissionRepository;
        private readonly IBaseReposiotry<RolePermissions> _rolePermissionRepository;
        private readonly ILogger<DeleteRolesHandler> _logger;
        private readonly IMapper _mapper;
        private readonly UserDbContext _dbContext;

        public DeleteRolesHandler(IBaseReposiotry<Roles> permissionRepository,
            IBaseReposiotry<RolePermissions> rolePermissionRepository,
            ILogger<DeleteRolesHandler> logger,
            IMapper mapper,
            UserDbContext dbContext)
        {
            _permissionRepository = permissionRepository;
            _rolePermissionRepository = rolePermissionRepository;
            _logger = logger;
            _mapper = mapper;
            _dbContext = dbContext;
        }

        public async Task<ApiResult> Handle(DeleteRolesReqsultDto request, CancellationToken cancellationToken)
        {
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    var role = await _permissionRepository.GetAsync(x=>x.RolesId==request.RolesId );
                    if (role == null)
                    {
                        return ApiResult.Error("角色不存在");
                    }
                    _dbContext.Set<Roles>().Remove(role);
                    await _dbContext.SaveChangesAsync();
                    var list = await _rolePermissionRepository.GetsAll(x => x.RoleId == request.RolesId);
                    _dbContext.Set<RolePermissions>().RemoveRange(list);
                    await _dbContext.SaveChangesAsync();
                    tran.Complete();
                    return ApiResult.Ok();
                }
                finally
                {
                    tran.Complete();
                }

            }
        }
    }
}
public class DeleteRolesReqsultDto:IRequest<ApiResult>
{
    public int RolesId { get; set; }
}
